import { AuthenticatedRequest } from './authenticatedRequest';
import type { ApiResponse } from '../utils/axiosInstance';
import { AxiosManager, checkAuthStatus } from '../utils/axiosInstance';

/**
 * 位置数据接口
 */
export interface LocationData {
  latitude: number;
  longitude: number;
  accuracy?: number;
  altitude?: number | null;
  altitudeAccuracy?: number | null;
  heading?: number | null;
  speed?: number | null;
  timestamp: string;
}

/**
 * 位置服务类
 */
export class LocationService {
  /**
   * 发送位置数据到服务器（实时消息）
   * @param locationData 位置数据
   * @returns API响应
   */
  public static async sendLocationToServer(locationData: LocationData): Promise<ApiResponse<void>> {
    try {
      // 显式检查认证状态
      console.log('[LocationService] 检查认证状态...');
      checkAuthStatus();
      
      if (!AxiosManager.isAuthenticated()) {
        throw new Error('用户未登录，无法发送位置数据');
      }
      
      const token = AxiosManager.getAuthToken();
      console.log('[LocationService] 认证令牌存在:', !!token);
      
      // 数据验证，确保必填字段存在且有效
      if (locationData.latitude === undefined || locationData.longitude === undefined) {
        throw new Error('位置数据缺少必要的经纬度信息');
      }
      
      console.log('[LocationService] 准备发送位置数据:', locationData);
      
      // 直接发送位置数据对象
      const requestData = {
        latitude: locationData.latitude,
        longitude: locationData.longitude,
        accuracy: locationData.accuracy,
        altitude: locationData.altitude,
        altitudeAccuracy: locationData.altitudeAccuracy,
        heading: locationData.heading,
        speed: locationData.speed
      };
      
      // 更新为新的API路径
      const response = await AuthenticatedRequest.post<void>(
        '/api/location/realtimeMsg',
        requestData
      );
      
      console.log('[LocationService] 位置数据发送成功');
      return response;
    } catch (error) {
      console.error('[LocationService] 位置数据发送失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户当前位置信息
   * @returns 用户当前位置数据
   */
  public static async getCurrentLocationInfo(): Promise<ApiResponse<LocationData>> {
    try {
      // 显式检查认证状态
      console.log('[LocationService] 检查认证状态...');
      checkAuthStatus();
      
      if (!AxiosManager.isAuthenticated()) {
        throw new Error('用户未登录，无法获取位置数据');
      }
      
      const token = AxiosManager.getAuthToken();
      console.log('[LocationService] 认证令牌存在:', !!token);
      
      console.log('[LocationService] 准备获取用户当前位置信息...');
      
      // 发送GET请求获取用户当前位置
      const response = await AuthenticatedRequest.get<LocationData>('/api/location/current');
      
      console.log('[LocationService] 获取用户当前位置信息成功:', response.data);
      return response;
    } catch (error) {
      console.error('[LocationService] 获取用户当前位置信息失败:', error);
      throw error;
    }
  }

  /**
   * 获取当前位置并发送到服务器
   * @returns Promise<void>
   */
  public static async getCurrentLocationAndSend(): Promise<void> {
    return new Promise((resolve, reject) => {
      try {
        // 预先检查认证状态，避免获取位置后才发现未登录
        console.log('[LocationService] 预先检查认证状态...');
        checkAuthStatus();
        
        if (!AxiosManager.isAuthenticated()) {
          throw new Error('用户未登录，无法发送位置数据');
        }
        
        if (!navigator.geolocation) {
          const error = new Error('浏览器不支持地理位置功能');
          console.error('[LocationService]', error.message);
          reject(error);
          return;
        }

        console.log('[LocationService] 正在获取位置信息...');
        navigator.geolocation.getCurrentPosition(
          async (position) => {
            try {
              // 确保经纬度存在
              if (position.coords.latitude === undefined || position.coords.longitude === undefined) {
                throw new Error('获取的位置数据缺少经纬度信息');
              }
              
              const locationData: LocationData = {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                accuracy: position.coords.accuracy || undefined,
                altitude: position.coords.altitude,
                altitudeAccuracy: position.coords.altitudeAccuracy,
                heading: position.coords.heading,
                speed: position.coords.speed,
                timestamp: new Date().toISOString()
              };

              await this.sendLocationToServer(locationData);
              console.log('[LocationService] 位置获取和发送成功');
              resolve();
            } catch (error) {
              console.error('[LocationService] 处理位置数据时出错:', error);
              reject(error);
            }
          },
          (error) => {
            console.error('[LocationService] 获取位置信息失败:', error);
            let errorMessage = '获取位置失败';
            
            switch (error.code) {
              case error.PERMISSION_DENIED:
                errorMessage = '用户拒绝了位置请求';
                break;
              case error.POSITION_UNAVAILABLE:
                errorMessage = '位置信息不可用';
                break;
              case error.TIMEOUT:
                errorMessage = '获取位置超时';
                break;
            }
            
            reject(new Error(errorMessage));
          },
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0
          }
        );
      } catch (error) {
        console.error('[LocationService] 初始化位置发送失败:', error);
        reject(error);
      }
    });
  }
}